/*
 * Copyright (c) 2014 laidian. All Rights Reserved.
 * 
 * @author yaoyuming
 * 
 * @date 2020-03-23 17:32
 */
package com.yao.common.helper;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import lombok.extern.slf4j.Slf4j;

/**
 * @author yaoyuming
 * @date 2020/03/23 17:32
 */
@Slf4j
public class RequestHelper {
    /**
     * 获取 HttpServletRequest实例
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        return attributes == null ? null : attributes.getRequest();
    }

    /**
     * 获取 HttpServletResponse实例
     *
     * @return
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        return attributes == null ? null : attributes.getResponse();
    }

    public static String getBody() {
        return getBody(getRequest());
    }

    /**
     * 功能描述 : 获取body内容
     * 
     * @param request
     * @author yaoyuming
     * @date 2020/6/3 0003
     * @return {@link String}
     */
    public static String getBody(ServletRequest request) {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String str = "";
            while ((str = reader.readLine()) != null) {
                sb.append(str);
            }
        } catch (IOException e) {
            log.error("获取请求body出错.{}", e.getMessage());
            e.printStackTrace();
        }
        return sb.toString();
    }

}